
package com.kaching.gae.client

import java.net.URL;

import com.kaching.api.client.model._
import _root_.com.twolattes.json._
import _root_.com.twolattes.json.TwoLattes.createMarshaller
import com.kaching.twitter.KCUser
import com.kaching.gae.client.KcClient._
import com.google.appengine.api.urlfetch._
import KcCredentials.apiKey

class UserPost (user: KCUser, path: String, properties: Map[String, String]) {
  val fullPath = KcClient.userBaseUrl + user.kcId + path
  println("using full path " + fullPath)
  private val request = new HTTPRequest(new URL(fullPath), HTTPMethod.POST)
  request.addHeader(new HTTPHeader(apiKeyName, apiKey))
  request.addHeader(new HTTPHeader(remoteKeyName, user.kcKey))
  val payload = properties map {case(k, v) => k + "=" + v} mkString "&"
  println("using payload " + payload)
  request.setPayload(payload.getBytes)
  
  private def act() = {
    val response : HTTPResponse = URLFetchServiceFactory.getURLFetchService.fetch(request)
    println("return code = " + response.getResponseCode)
    val stringValue = new String(response.getContent)
    println("return value = " + stringValue)
    stringValue
  }
  
  def actOrder : OrderStatus = {
    val response = act()
    val os : OrderStatus = {
      val marshaller = createMarshaller(classOf[OrderStatus])
      val json = Json.fromString(response).asInstanceOf[Json.Object]
      try {
    	marshaller.unmarshall(json)
      } catch {
        case e => {
          println(json.toString)
          e.printStackTrace
          null
        }
      }
    }
    os
  }
}
